package by.epam.trenings.vkphotorest.adapters;

import by.epam.trenings.vkphotorest.content.contract.TaskContract;
import by.epam.trenings.vkphotorest.fragments.FullScreenFragmentContent;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class CursorFragmentPagerAdapter extends FragmentPagerAdapter {

	private Cursor mCursor;

	public CursorFragmentPagerAdapter(Context context, FragmentManager fm,
			Cursor cursor) {
		super(fm);
		mCursor = cursor;
	}

	@Override
	public int getCount() {
		int count;
		if (mCursor == null) {
			count = 0;
		} else {
			count = mCursor.getCount();
		}
		return count;
	}

	public Cursor getCursor() {
		return mCursor;
	}

	public void closeCursor() {
		if (!mCursor.isClosed()) {
			mCursor.close();
		}
	}

	public void changeCursor(Cursor cursor) {
		Cursor old = swapCursor(cursor);
		if (old != null) {
			old.close();
		}
	}

	public Cursor swapCursor(Cursor newCursor) {
		if (newCursor == mCursor) {
			return null;
		}
		Cursor oldCursor = mCursor;
		mCursor = newCursor;

		return oldCursor;
	}

	@Override
	public Fragment getItem(int position) {
		if (getCount() != 0) {
			FullScreenFragmentContent content = new FullScreenFragmentContent();
			Bundle arguments = new Bundle();
			mCursor.moveToPosition(position);

			String src = mCursor.getString(mCursor
					.getColumnIndex(TaskContract.PhotosColumns.SRC_BIG));
			if (src.equals("")) {
				src = mCursor.getString(mCursor
						.getColumnIndex(TaskContract.PhotosColumns.SRC));
			}
			arguments.putString(FullScreenFragmentContent.EXTRA_PHOTO_SRC, src);
			String discription = mCursor.getString(mCursor
					.getColumnIndex(TaskContract.PhotosColumns.DISCRIPTION));

			arguments.putString(
					FullScreenFragmentContent.EXTRA_PHOTO_DISCRIPTION,
					discription);
			content.setArguments(arguments);
			return content;
		} else {
			return null;
		}
	}

}
